package com.shengruan.admin.action;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.shengruan.admin.jdbc.ArticleJdbc;
import com.shengruan.admin.vo.Article;
import com.shengruan.common.BaseAction;
import com.shengruan.common.Constants;
import com.shengruan.common.Function;
import com.shengruan.framework.pager.Pager;


public class ArticleAction extends BaseAction{

	private ArticleJdbc articleJdbc = (ArticleJdbc)this.getJdbc(ArticleJdbc.class);
    
    
    public void loadAdd() throws Exception {
        this.setRequest("ARTICLE_TYPE_MAP", Constants.ARTICLE_TYPE_MAP);
        this.forward("/admin/article/edit.jsp");
    }

	/***
	 * 编辑初始化
	 */
	public void initEdit() throws Exception 
	{
        this.setRequest("ARTICLE_TYPE_MAP", Constants.ARTICLE_TYPE_MAP);
		int id = Integer.parseInt(input("id"));
		Article article = articleJdbc.getById(id);
		this.setRequest("article", article);
		this.forward("/admin/article/edit.jsp");
	}
	/***
	 * 获得列表
	 * @throws ServletException
	 * @throws IOException
	 */
	public void list() throws Exception 
	{
		int currentPage = 1;
		try
		{
			currentPage = Integer.parseInt(input("currentPage"));
		}
		catch(Exception ex)
		{

		}
		Pager pager = new Pager(currentPage,articleJdbc.getRows(),10);
		List<Article> articleList = articleJdbc.findWithPage(currentPage, 10);
		this.setRequest("pager", pager);
		this.setRequest("articleList", articleList);
        this.setRequest("ARTICLE_TYPE_MAP", Constants.ARTICLE_TYPE_MAP);
		this.forward("/admin/article/list.jsp");
	}

	/***
	 * 编辑文章
	 */
	@SuppressWarnings("unchecked")
	public void edit() throws Exception 
	{
		int id = 0;
		int type = 1;
		String fileType = "";
		String fileName = "";
		String fileUrl = "";
		String title =  "";
		String content = "";
		String postTime = "";
		String pic = "";
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(isMultipart)
		{
			// 创建一个文件上传的处理器
			ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
			try {
				request.setCharacterEncoding("UTF-8");    
				List<FileItem> items = upload.parseRequest(request);
				for(int i=0;i<items.size();i++){
					FileItem item=(FileItem)items.get(i);
					if(item.isFormField())
					{
						String formName = item.getFieldName();
						if("title".equals(formName))
						{
							title = item.getString("UTF-8");
						}
						else if("content".equals(formName))
						{
							content = item.getString("UTF-8");
						}
						else if("postTime".equals(formName))
						{
							postTime = item.getString("UTF-8"); 
						}
						else if("type".equals(formName))
						{
							type = Integer.parseInt(item.getString("UTF-8"));
						}
						else if("articleId".equals(formName))
						{
							try
							{
								id = Integer.parseInt(item.getString("UTF-8"));
							}
							catch(Exception ex)
							{
								
							}
						}
						else if("pic".equals(formName))
						{
							pic = item.getString("UTF-8");
						}
					}
					else
					{
						fileName=takeOutFileName(item.getName());
						if(fileName!=null&&!"".equals(fileName))
						{
							String [] fns = fileName.split("\\u002e");
							int fnLenght = fns.length;
							if(fnLenght==1)
							{
								fileUrl = String.valueOf(System.currentTimeMillis());
								fileType = "no";
								fileName = fns[0];
							}
							else
							{
								fileName = "";
								for(int k=0;k<fns.length-1;k++)
								{
									fileName = fileName+fns[k]+".";
								}
								fileName = fileName.substring(0,fileName.length()-1);
								fileType = fns[fnLenght-1].toLowerCase();
								fileUrl =System.currentTimeMillis()+"."+fileType;
							}

							File upFolder = new File(Constants.APP_PATH+File.separator+"uploadfiles"+File.separator+"pic"+File.separator);
							upFolder.mkdirs();
							File uploadedFile = new File(upFolder.getPath()+File.separator+fileUrl);
							item.write(uploadedFile);
						}
						
					}
				}
			}
			catch (FileUploadException e) 
			{
				e.printStackTrace();
			} catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		Article article = new Article();
		if(fileUrl==null||"".equals(fileUrl))
			article.setPic(pic);
		else
			article.setPic(fileUrl);
		article.setId(id);
		article.setType(type);
		article.setTitle(title);
		article.setContent(content);
		article.setPostTime(postTime);

		if(id==0)
		{

			article.setPostTime(Function.getDetailDate());
			articleJdbc.save(article);
		}
		else
		{
			articleJdbc.update(article);
		}
        //初始化首页公告
        Constants.articleList =articleJdbc.findAll();

		this.redirect("/admin/article/article.ac");
	}


	/**
	 * 从文件路径中取出文件名
	 * @param filePath
	 * @return
	 */
	private String takeOutFileName(String filePath){
		int pos=filePath.lastIndexOf(File.separator);
		if (pos>0){
			return filePath.substring(pos+1);
		}
		else{
			return filePath;
		}
	}
	/***
	 * 根据ID删除
	 */
	public void deleteById() throws Exception 
	{
		int currentPage = 1;
		try
		{
			currentPage = Integer.parseInt(input("currentPage"));
		}
		catch(Exception ex)
		{

		}
		int id = Integer.parseInt(input("id"));
		articleJdbc.deleteById(id);

        //初始化首页公告
        Constants.articleList =articleJdbc.findAll();

		this.redirect("/admin/article/article.ac?currentPage="+currentPage);
	}
}
